package com.miui.theme.custom.data

import android.content.Context
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import kotlinx.serialization.decodeFromString // <--- 添加这一行
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json

private val Context.dataStore by preferencesDataStore(name = "db_config")

class ConfigDataStore(context: Context) {
    private val dataStore = context.dataStore

    companion object {
        private val CONFIG_KEY = stringPreferencesKey("database_config")
    }

    val config: Flow<DatabaseConfig?> = dataStore.data
        .map { preferences ->
            preferences[CONFIG_KEY]?.let {
                try {
                    Json.decodeFromString<DatabaseConfig>(it)
                } catch (e: Exception) {
                    null
                }
            } ?: DatabaseConfig() // 提供默认值
        }

    suspend fun saveConfig(config: DatabaseConfig) {
        dataStore.edit { preferences ->
            preferences[CONFIG_KEY] = Json.encodeToString(config)
        }
    }
}